import { _decorator, Component, director, instantiate, Label, Node, Pool, Prefab, ProgressBar, randomRangeInt, PhysicsSystem, physics, PhysicsSystem2D, EPhysics2DDrawFlags, UITransform, Widget, find, Sprite, dynamicAtlasManager, Color, SpriteFrame, resources, random, DynamicAtlasManager, Button } from 'cc';
import { AudioManager, Core } from './Core/Core';
import { PlayerManager } from './PlayerManager';

import { EEnemy, EState, EEvent, EGame, EntityType, EPlayerType, EScene, EGameMode, EPet, EWeather, ESkill, EGeneralSkill } from './Config/Enum';
import { ResourceManager } from './Core/ResourceManager';
import { EnemyManager } from './EnemyManager';
import ObjectPoolManager from './Core/ObjectPoolManager';
import { EXPPerEnemy, GoldPerEnemy, RenownPerEnemy } from './Config/Config';
import { StageConfig } from './Config/StageConfig';

import { EItemType, IItem } from './Item/Item';
import { Context } from './Context';
import { Coin } from './Item/Coin';
import { SkillManager } from './Skill/SkillManager';
import { Header } from './Header';
import { WallManager } from './WallManager';
import { PetManager } from './PetManager';
import { PetData } from './PetData';
import { GeneralSkillConfig } from './Config/SkillConfig';

const { ccclass, property } = _decorator;

@ccclass('BattleManager')
export class BattleManager extends Component {
    // ====================== 单例核心代码 ======================
    private static _instance: BattleManager | null = null;
    goldPercent: string;
    expPercent: string;
    renownPercent: string;
    wallHpBegin: any;
    wallHpEnd: any;
    public static get Instance(): BattleManager {
        if (!BattleManager._instance) {
            console.error("BattleManager 尚未初始化！请确保场景中存在 BattleManager 节点");
        }
        return BattleManager._instance!;
    }

    // ====================== 节点引用 (代码查找) ======================
    ndEnemies: Node = null!;
    ndPets: Node = null!;
    ndPlayers: Node = null!;
    ndSkills: Node = null!;
    ndTexts: Node = null!;
    ndGameEndView: Node = null!;
    ndEnemyProgressBar: Node = null!;
    ndHeader: Node = null!;
    ndTimer: Node = null!;
    ndTips: Node = null!;
    ndPauseView: Node = null!;
    ndItems: Node = null!;
    ndDefault: Node = null!;
    ndWall: Node = null!;
    ndBtnGeneralSkill: Node = null!;

    // ====================== 逻辑组件引用 ======================
    wm: WallManager = null!; // [修复] 找回 WallManager
    
    // ====================== 状态与数据 ======================
    private _speedFactor: number = 1;
    private _speedLevels: number[] = [1, 2, 3];
    private _currentSpeedIndex: number = 0;
    
    // 游戏时间限制
    private timeLimit: number = 180;
    private currentTime: number = 0;
    private isTimeRunning: boolean = false;

    // 波次管理
    enemyConfig: any = null; // [修复] 找回 enemyConfig
    private currentWaveTotalEnemies: number = 0;
    private currentWaveDeadEnemies: number = 0;
    private currentWaveIndex: number = 0;
    private totalWaves: number = 0;
    private waveConfigs: any[] = [];
    private bossConfig: EntityType[] = [];
    private waveTimer: number = 0;
    
    // BOSS管理
    private bossSpawnTimer: number = 0;
    private isWaitingForBoss: boolean = false;
    private nextBossIndex: number = 0;

    // 游戏数据
    playerList: PlayerManager[] = [];
    nearestEnemy: Node = null;
    sortedEnemies: Node[] = [];
    lootList: IItem[] = [];
    playerDamageMap: Map<EPlayerType, number> = new Map();
    
    stage: number = 1;
    mode: EGameMode = EGameMode.Normal;
    gold: number = 0;
    renown: number = 0;
    exp: number = 0;
    food: number = 0;
    prisoner: number = 0;
    damageTotal: number = 0;
    numOfDeadEnemies: number = 0;
    numOfEnemies: number = 0;
    
    isGameEnd: boolean = false;
    gameResult: boolean = false;
    shouldUpdate: boolean = false;
    autoDazhao: boolean = false;
    weather: EWeather = EWeather.Sunny;
    
     goldPerEnemy: number = GoldPerEnemy;
    private lbStage: Label = null;
    
    protected onLoad(): void {
        console.log("BattleManager onLoad");
        if (BattleManager._instance && BattleManager._instance !== this) {
            this.destroy();
            return;
        }
        BattleManager._instance = this;

        // 播放战斗音乐
        AudioManager.Instance.playMusic("battle_bgm");

        // [关键] 代码绑定节点
        this.bindNodes();

        // [修复] 获取 WallManager 组件
        if (this.ndWall) {
            this.wm = this.ndWall.getComponent(WallManager);
            this.wallHpEnd = this.ndWall.getComponent(WallManager).hp
        }

        // UI 初始化
        if (this.node.getChildByName("Stage")) {
            this.lbStage = this.node.getChildByName("Stage").getComponent(Label);
            this.lbStage.string = "第 " + Core.Instance.currentStage + " 关";
        }
        
        // 数据初始化
        this.lootList = [];
        for (const playerType of Core.Instance.selectedPlayers) {
            this.playerDamageMap.set(playerType as EPlayerType, 0);
        }

        // 隐藏不必要的UI
        if(this.ndGameEndView) this.ndGameEndView.active = false;
        if(this.ndPauseView) this.ndPauseView.active = false;

        // 全局上下文
        Context.ndTips = this.ndTips;
        Context.ndDefault = this.ndDefault;
    }

    private bindNodes() {
        // 使用 getChildByName 查找节点
        this.ndPlayers = this.node.getChildByName("Players");
        this.ndEnemies = this.node.getChildByName("Enemies");
        this.ndSkills = this.node.getChildByName("Skills");
        this.ndPets = this.node.getChildByName("Pets");
        this.ndTexts = this.node.getChildByName("Texts");
        this.ndGameEndView = this.node.getChildByName("GameEndView");
        this.ndEnemyProgressBar = this.node.getChildByName("EnemyProgress");
        this.ndItems = this.node.getChildByName("Items");
        this.ndTimer = this.node.getChildByName("Timer");
        this.ndWall = this.node.getChildByName("Wall");
        this.ndBtnGeneralSkill = this.node.getChildByName("GeneralSkill");
        this.ndTips = this.node.getChildByName("Tips");
        this.ndDefault = this.node.getChildByName("Default");
        this.ndHeader = this.node.getChildByName("Header");
        this.ndPauseView = this.node.getChildByName("PauseView");
    }

    protected onEnable(): void {
        Core.Instance.event.on(EEvent.EnemyDie, this.onEnemyDie, this);
        Core.Instance.event.on(EEvent.DamageDeal, this.onDamageDeal, this);

        // 初始化速度
        this._speedFactor = Core.Instance.lastSpeedUp || 1;
        this._currentSpeedIndex = this._speedLevels.indexOf(this._speedFactor);
        if (this._currentSpeedIndex === -1) {
            this._currentSpeedIndex = 0;
            this._speedFactor = this._speedLevels[0];
        }
        if(this.ndHeader) this.ndHeader.getComponent(Header).setSpeed(this._speedFactor);
        
        director.getScheduler().setTimeScale(this._speedFactor);
    }

    protected onDisable(): void {
        AudioManager.Instance.stopMusic();
        Core.Instance.event.off(EEvent.EnemyDie, this.onEnemyDie, this);
        Core.Instance.event.off(EEvent.DamageDeal, this.onDamageDeal, this);
        this.resetGameSpeed();
    }

    protected onDestroy(): void {
        if (BattleManager._instance === this) {
            BattleManager._instance = null;
        }
    }

    start() {
        this.sortEnemies();
        this.initTimer();
        this.weather = Core.Instance.weather;

        // Tips显示
        if (this.ndTips) this.ndTips.active = Core.Instance.isNewPlayer;

        this.shouldUpdate = true;
        this.mode = Core.Instance.currentMode;
        this.stage = Core.Instance.currentStage;

        // 初始化模式
        switch (this.mode) {
            case EGameMode.Normal:
                this.initNormalMode();
                break;
            case EGameMode.Endless:
                this.initEndlessMode();
                break;
            case EGameMode.Wood:
                this.initWoodMode();
                break;
            case EGameMode.Gold:
                this.initGoldMode();
                break;
            case EGameMode.Gem:
                this.initGemMode();
                break;
            default:
                console.error("未知游戏模式:", this.mode);
                this.initNormalMode();
                break;
        }
        
        // 启动怒气回复定时器（1秒一次）
        this.schedule(this.regenRageForPlayers, 1.0);
        // 启动低频排序（3秒一次）
        this.schedule(this.sortEnemies, 3.0);
    }

    update(dt: number) {
        if (!this.shouldUpdate) return;
        const scaledDt = dt; 

        if (this.isTimeRunning) {
            this.updateTimer(scaledDt);
        }

        this.updateWaveLogic(scaledDt);
    }

    private updateWaveLogic(dt: number) {
        if (this.currentWaveIndex > 0 && 
            this.currentWaveIndex < this.totalWaves &&
            this.currentWaveDeadEnemies > 0) {
            
            this.waveTimer += dt;
            const waveCompleted = this.currentWaveDeadEnemies >= this.currentWaveTotalEnemies;
            
            if (waveCompleted || this.waveTimer >= 10) {
                this.startNextWave();
            }
        }
        
        if (this.isWaitingForBoss) {
            this.bossSpawnTimer += dt;
            if (this.bossSpawnTimer >= 10) {
                this.spawnNextBoss();
            }
        }
    }

    // ====================== 速度控制 ======================
    
    getCurrentSpeed(): number {
        return this._speedFactor;
    }

    onButtonSpeedUp() {
        this._currentSpeedIndex = (this._currentSpeedIndex + 1) % this._speedLevels.length;
        this._speedFactor = this._speedLevels[this._currentSpeedIndex];
        Core.Instance.lastSpeedUp = this._speedFactor;
        
        director.getScheduler().setTimeScale(this._speedFactor);
        this.updateAllEntitiesSpeed();
        
        if(this.ndHeader) this.ndHeader.getComponent(Header).setSpeed(this._speedFactor);
    }

    private updateAllEntitiesSpeed() {
        this.playerList.forEach(p => p && p.setSpeedFactor && p.setSpeedFactor(this._speedFactor));
        this.ndEnemies.children.forEach(n => {
            const e = n.getComponent(EnemyManager);
            if(e) e.setSpeedFactor(this._speedFactor);
        });
        this.ndSkills.children.forEach(n => {
            const s = n.getComponent(SkillManager);
            if(s) s.setSpeedFactor(this._speedFactor);
        });
        if(this.ndPets) {
            this.ndPets.children.forEach(n => {
                const pm = n.getComponent(PetManager);
                if(pm) pm.setSpeedFactor(this._speedFactor);
            });
        }
    }

    private resetGameSpeed() {
        this._speedFactor = 1;
        this._currentSpeedIndex = 0;
        director.getScheduler().setTimeScale(1);
    }

    // ====================== 计时器 ======================
    private initTimer() {
        this.timeLimit = 360; 
        if(Core.Instance.currentStage > 15) this.timeLimit = 500;
        this.currentTime = this.timeLimit;
        this.isTimeRunning = true;
        this.updateTimerUI();
    }

    private updateTimer(dt: number) {
        this.currentTime -= dt;
        this.updateTimerUI();
        if (this.currentTime <= 0) {
            this.currentTime = 0;
            this.isTimeRunning = false;
            this.onTimeUp();
        }
    }

    private updateTimerUI() {
        if (!this.ndTimer || !this.ndTimer.isValid) return;
        const timerLabel = this.ndTimer.getComponent(Label);
        if (!timerLabel) return;
        
        const totalSeconds = Math.ceil(this.currentTime);
        const minutes = Math.floor(totalSeconds / 60);
        const seconds = totalSeconds % 60;
        timerLabel.string = `${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
    }

    private onTimeUp() {
        Core.Instance.showLabel("时间到！征战失败");
        this.scheduleOnce(() => {
            this.gameResult = false;
            this.endGame(false);
        }, 1);
    }

    // ====================== 模式初始化 ======================
    private initCommonSetup(mapId: number) {
        this.initMap(mapId);
        this.generatePlayer();
        this.generatePet();
        this.loadGeneralSkill();
    }

    private initNormalMode() {
        Core.Instance.currentMode = EGameMode.Normal;
        this.initCommonSetup(1);
        this.loadWaveConfig();
        this.startNextWave();
    }

    private initEndlessMode() {
        Core.Instance.currentMode = EGameMode.Endless;
        this.initCommonSetup(2);
        this.configureEndlessWaves();
        this.startNextWave();
    }

    private initGoldMode() {
        Core.Instance.currentMode = EGameMode.Gold;
        this.goldPerEnemy = 10 * GoldPerEnemy;
        this.initCommonSetup(2);
        this.loadWaveConfig();
        this.startNextWave();
    }

    private initWoodMode() {
        Core.Instance.currentMode = EGameMode.Wood;
        this.numOfEnemies = 1;
        this.initCommonSetup(1);
        this.generateWoodenEnemy();
    }

    private initGemMode() { }

    private initMap(bgIndex: number) {
        const path = `pic/bg/${bgIndex}/spriteFrame`;
        ResourceManager.Instance.loadRes<SpriteFrame>(path, SpriteFrame).then(sf => {
             if(this.node && this.node.isValid && this.node.getChildByName("Map")) {
                 this.node.getChildByName("Map").getComponent(Sprite).spriteFrame = sf;
             }
        });
    }

    // ====================== 波次与敌人生成 ======================
    configureEndlessWaves() {
        const selectedEnemies = Core.Instance.endlessEnemies;
        this.waveConfigs = [
            { enemies: this.createWaveEnemies(selectedEnemies, 100) },
            { enemies: this.createWaveEnemies(selectedEnemies, 100) },
            { enemies: this.createWaveEnemies(selectedEnemies, 100) }
        ];
        
        const boss1 = Core.Instance.endlessBosses[0];
        const boss2 = Core.Instance.endlessBosses[1];
        this.bossConfig = [boss1, boss2];
        this.totalWaves = this.waveConfigs.length;
        this.numOfEnemies = 300 + this.bossConfig.length;
    }

    private createWaveEnemies(enemyTypes: EEnemy[], totalCount: number): { [key: string]: number } {
        const waveEnemies: { [key: string]: number } = {};
        const baseCount = Math.floor(totalCount / enemyTypes.length);
        let remainder = totalCount % enemyTypes.length;
        
        for (const enemyType of enemyTypes) {
            let count = baseCount;
            if (remainder > 0) { count++; remainder--; }
            waveEnemies[enemyType] = count;
        }
        return waveEnemies;
    }

    loadWaveConfig() {
        let config = StageConfig[Core.Instance.currentMode];
        if (!config) return;
        
        // [修复] 将配置赋值给类属性
        this.enemyConfig = config.stage[Core.Instance.currentStage];
        if (!this.enemyConfig) return;

        this.waveConfigs = this.enemyConfig.waves || [];
        this.bossConfig = this.enemyConfig.bosses || [];
        this.totalWaves = this.waveConfigs.length;
        
        this.numOfEnemies = 0;
        for (const wave of this.waveConfigs) {
            for (const enemyType in wave.enemies) {
                this.numOfEnemies += wave.enemies[enemyType];
            }
        }
        this.numOfEnemies += this.bossConfig.length;
    }

    private startNextWave() {
        if (this.currentWaveIndex >= this.totalWaves) return;
        
        this.waveTimer = 0;
        this.currentWaveDeadEnemies = 0;
        const waveNum = this.currentWaveIndex + 1;
        Core.Instance.showLabel(`第 ${waveNum} / ${this.totalWaves} 波敌军来袭！`);
        
        const waveConfig = this.waveConfigs[this.currentWaveIndex];
        this.currentWaveTotalEnemies = 0;
        for (const enemyType in waveConfig.enemies) {
            this.currentWaveTotalEnemies += waveConfig.enemies[enemyType];
        }
        
        this.generateWaveEnemies(waveConfig);
        this.currentWaveIndex++;
        this.checkBossSpawning();
    }

    private generateWaveEnemies(waveConfig: any) {
        const enemyQueue: EntityType[] = [];
        for (const enemyType in waveConfig.enemies) {
            const count = waveConfig.enemies[enemyType];
            for (let i = 0; i < count; i++) enemyQueue.push(enemyType as EntityType);
        }
        // 洗牌
        for (let i = enemyQueue.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [enemyQueue[i], enemyQueue[j]] = [enemyQueue[j], enemyQueue[i]];
        }
        // 生成
        for (let i = 0; i < enemyQueue.length; i++) {
            if (this.isGameEnd) break;
            this.scheduleOnce(() => {
                this.spawnEnemy(enemyQueue[i], false);
            }, i * 0.8);
        }
    }

    private spawnEnemy(enemyType: EntityType, isBoss: boolean) {
        if (this.isGameEnd) return;
        
        const enemy = ObjectPoolManager.Instance.get(enemyType);
        if (!enemy) return;
        
        const em = enemy.getComponent(EnemyManager);
        if (!em) return;

        em.setSpeedFactor(this._speedFactor);
        
        let isElite = false;
        if (Core.Instance.currentMode === EGameMode.Endless && !isBoss) {
            isElite = Math.random() < (Core.Instance.currentStage * 0.05);
        }

        if (isBoss) {
            enemy.setPosition(0, 300, 0);
        } else {
            const randomX = randomRangeInt(-Core.Instance.screenBounds.maxX/2, Core.Instance.screenBounds.maxX/2);
            const randomY = 0.74 * Core.Instance.screenBounds.maxY/2;
            enemy.setPosition(randomX, randomY, 0);
        }

        em.init(enemyType, isElite, isBoss);
    }

    private checkBossSpawning() {
        const totalWaves = this.totalWaves;
        const currentWave = this.currentWaveIndex;
        
        if (totalWaves === 2 && currentWave === 2) {
            this.scheduleOnce(() => this.spawnBoss(0), this.currentWaveTotalEnemies * 0.8 + 2);
        } else if (totalWaves === 3) {
            if (currentWave === 2) {
                this.scheduleOnce(() => {
                    this.spawnBoss(0);
                    this.scheduleOnce(() => this.startNextWave(), 12);
                }, this.currentWaveTotalEnemies * 0.8 + 2);
            } else if (currentWave === 3) {
                this.scheduleOnce(() => this.spawnBoss(1), this.currentWaveTotalEnemies * 0.8 + 2);
            }
        }
    }

    private spawnBoss(bossIndex: number) {
        if (bossIndex >= this.bossConfig.length) return;
        const bossType = this.bossConfig[bossIndex];
        Core.Instance.showLabel('敌将 来袭!', Color.RED);
        this.spawnEnemy(bossType, true);
    }

    private spawnNextBoss() {
        if (this.nextBossIndex >= this.bossConfig.length) {
            this.isWaitingForBoss = false;
            return;
        }
        const bossType = this.bossConfig[this.nextBossIndex];
        Core.Instance.showLabel('BOSS 来袭!', Color.RED);
        this.spawnEnemy(bossType, true);
        this.nextBossIndex++;
        this.isWaitingForBoss = false;
        
        if (this.totalWaves === 3 && this.nextBossIndex === 1) {
            this.scheduleOnce(() => this.startNextWave(), 10);
        }
    }

    // ====================== 战斗逻辑 ======================

    onEnemyDie(enemy: EnemyManager) {
        this.numOfDeadEnemies++;
        this.currentWaveDeadEnemies++;
        this.exp += EXPPerEnemy;
        this.renown += RenownPerEnemy;
        
        const coinNode = ObjectPoolManager.Instance.get(EItemType.Coin);
        if (coinNode) {
            coinNode.setWorldPosition(enemy.node.worldPosition.x, enemy.node.worldPosition.y - 25, 0);
            const coin = coinNode.getComponent(Coin);
            if(coin) coin.init();
        }
        
        this.updateEnemyProgressBar();
        if (this.nearestEnemy === enemy.node) this.sortEnemies();
        this.checkWinCondition();
    }

    private checkWinCondition() {
        if (this.currentWaveIndex >= this.totalWaves && 
            !this.isWaitingForBoss &&
            this.numOfDeadEnemies >= this.numOfEnemies) {
            this.scheduleEndGame();
        }
    }

    private regenRageForPlayers() {
        for (const player of this.playerList) {
            if (player && player.state !== EState.Die) {
                player.addRage(player.rageRegen);
            }
        }
    }

    scheduleEndGame() {
        if (!this.isGameEnd) {
            this.isGameEnd = true;
            console.log("胜利结算准备中...");
            this.scheduleOnce(() => {
                this.gameResult = true;
                this.endGame(true);
            }, 2);
        }
    }

    onDamageDeal(value: number, playerType: EPlayerType | string) {
        if(playerType === "null") return;
        const type = playerType as EPlayerType;
        const currentDamage = this.playerDamageMap.get(type) || 0;
        this.playerDamageMap.set(type, currentDamage + value);
        this.damageTotal += value;
        Core.Instance.event.emit(EEvent.DamageUpdateHeader, this);
    }

    updateEnemyProgressBar() {
        if(this.numOfEnemies > 0)
            this.ndEnemyProgressBar.getComponent(ProgressBar).progress = this.numOfDeadEnemies / this.numOfEnemies;
    }

    generatePlayer() {
        const positions = [
            { x: -150, y: 0 }, { x: -75, y: 0 }, { x: 0, y: 0 }, { x: 75, y: 0 }, { x: 150, y: 0 }
        ];
        const count = Core.Instance.selectedPlayers.size;
        let posIdxs: number[] = [];
        if (count === 1) posIdxs = [2];
        else if (count === 2) posIdxs = [1, 3];
        else if (count === 3) posIdxs = [1, 2, 3];
        else if (count === 4) posIdxs = [0, 1, 3, 4];
        else posIdxs = [0, 1, 2, 3, 4];

        let i = 0;
        Core.Instance.selectedPlayers.forEach((playerType) => {
            const node = ObjectPoolManager.Instance.get(playerType as EntityType);
            const pm = node.getComponent(PlayerManager);
            pm.init(playerType as EPlayerType);
            pm.setSpeedFactor(this._speedFactor);
            this.playerList.push(pm);
            const pos = positions[posIdxs[i] || 2];
            node.setPosition(pos.x, pos.y, 0);
            i++;
        });
    }

    generatePet() {
        const petPositions = [
            { x: -112.5, y: 0 }, { x: -37.5, y: 0 }, { x: 37.5, y: 0 }, { x: 112.5, y: 0 }
        ];
        let idx = 0;
        Core.Instance.pets.forEach((petData, petType) => {
            if (petData.assigned && idx < petPositions.length) {
                const pos = petPositions[idx];
                this.generateSinglePet(petType, petData, pos.x, pos.y);
                idx++;
            }
        });
    }

    private generateSinglePet(petType: EPet, petData: PetData, x: number, y: number) {
        const petNode = ObjectPoolManager.Instance.get(petType);
        if (!petNode) return;
        const pm = petNode.getComponent(PetManager);
        if (!pm) return;
        pm.init(petType);
        petNode.setPosition(x, y, 0);
        pm.setSpeedFactor(this._speedFactor);
    }

    generateWoodenEnemy() {
        const enemy = ObjectPoolManager.Instance.get(EEnemy.WoodenEnemy);
        if (!enemy) return;
        const em = enemy.getComponent(EnemyManager);
        em.initWoodenEnemy(EEnemy.WoodenEnemy);
        enemy.setPosition(0, 0);
    }

    sortEnemies() {
        this.sortedEnemies = [];
        this.nearestEnemy = null;
        if (!this.ndEnemies) return;
        for (const enemy of this.ndEnemies.children) {
            if(!enemy.active) continue;
            const em = enemy.getComponent(EnemyManager);
            if (!em || em.state === EState.Die) continue;
            this.sortedEnemies.push(enemy);
        }
        if (this.sortedEnemies.length === 0) return;
        this.sortedEnemies.sort((a, b) => a.position.y - b.position.y);
        this.nearestEnemy = this.sortedEnemies[0];
    }

    // ====================== 将军技能 ======================
    loadGeneralSkill() {
        let skill = Core.Instance.generalData.assignedActiveSkill;
        if (skill) {
            ResourceManager.Instance.loadRes<SpriteFrame>("pic/skill/GeneralSkill/" + skill + "/spriteFrame").then((sf) => {
                if(this.ndBtnGeneralSkill && this.ndBtnGeneralSkill.isValid)
                    this.ndBtnGeneralSkill.getComponent(Sprite).spriteFrame = sf;
            });
            const label = this.ndBtnGeneralSkill.getChildByName("Label");
            if(label) label.getComponent(Label).string = GeneralSkillConfig[skill].name;
            this.ndBtnGeneralSkill.active = true;
        } else {
            this.ndBtnGeneralSkill.active = false;
        }
    }

    releaseGeneralSkill() {
        switch (Core.Instance.generalData.assignedActiveSkill) {
            case EGeneralSkill.Wanjianqifa:
                this.releaseWanJianQiFa();
                break;
            case EGeneralSkill.Jinjijiagu:
                if(this.wm) this.wm.addHp(100);
                break;
        }
        Core.Instance.generalSkillMaxUses -= 1;
        if (Core.Instance.generalSkillMaxUses <= 0) {
            this.ndBtnGeneralSkill.active = false;
        }
    }

    releaseWanJianQiFa() {
        for (let i = 0; i < 100; i++) {
            let ndArrow = ObjectPoolManager.Instance.get(ESkill.Arrow);
            let x = randomRangeInt(-Core.Instance.screenBounds.maxX / 2, Core.Instance.screenBounds.maxX / 2);
            let y = -Core.Instance.screenBounds.maxY / 2 + randomRangeInt(-200, 200);
            ndArrow.setPosition(x, y, 0);
        }
    }

    // ====================== 结算 ======================
    endGame(isGameSuccess: boolean = true) {
        this.wallHpBegin = this.ndWall.getComponent(WallManager).hp
        this.isTimeRunning = false;
        this.resetGameSpeed();
        Core.Instance.isNewPlayer = false;
        this.isGameEnd = true;

        this.food = randomRangeInt(1, 10);
        Core.Instance.gold += this.gold;
        Core.Instance.generalData.addRenown(this.renown);
        Core.Instance.people += this.prisoner;
        Core.Instance.food += this.food;
        
        for (const player of Core.Instance.selectedPlayers) {
            Core.Instance.players.get(player).addExp(this.exp);
        }

        this.clearBattleData();

        if (isGameSuccess) {
            this.dropLoot();
            if (Core.Instance.currentStage === Core.Instance.modeMaxStage[this.mode]) {
                Core.Instance.modeMaxStage[this.mode] = Core.Instance.currentStage + 1;
            }
            Core.Instance.people += randomRangeInt(1, 50);
            Core.Instance.woodRock += randomRangeInt(1, 50);
        } else {
            Core.Instance.people = Math.max(0, Core.Instance.people - randomRangeInt(1, 50));
            Core.Instance.woodRock = Math.max(0, Core.Instance.woodRock - randomRangeInt(1, 50));
        }

        if(this.ndGameEndView) this.ndGameEndView.active = true;
        Core.Instance.save();
    }

    clearBattleData() {
        this.shouldUpdate = false;
        this.unscheduleAllCallbacks();
        this.playerList.forEach(player => player.node.active = false);
        if(this.ndEnemies) this.ndEnemies.children.forEach(enemy => enemy.active = false);
        ObjectPoolManager.Instance.reset();
    }

    dropLoot() {
        if (this.gameResult) {
            let dropCount = Core.Instance.calculateDropCountByStage(this.stage);
            const lootItems = Core.Instance.generateLootItems(this.stage, dropCount);
            lootItems.forEach(item => {
                Core.Instance.bag.addItem(item);
                this.lootList.push(item);
            });
        }
    }

    onButtonPause() {
        this.ndPauseView.active = true;
        director.pause();
    }

    onButtonResume() {
        this.ndPauseView.active = false;
        director.resume();
    }

    onButtonGoMain() {
        this.resetGameSpeed();
        director.resume();
        Core.Instance.save();
        this.clearBattleData();
        AudioManager.Instance.stopMusic();
        director.loadScene(EScene.Main);
    }
}